#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
主题: 大型数组运算
问题: 你需要在大数据集(比如数组或网格)上面执行计算。
提示 : 
    1. NumPy 是Python领域中很多科学与工程库的基础，同时也是被广泛使用的最大最复杂的模块
"""

import numpy as np
import time


def recipe1():
    """数组的重量级运算操作，可以使用 NumPy 库"""
    x = [1, 2, 3, 4]
    y = [5, 6, 7, 8]
    print(f"{x * 2 = }")
    print(f"{x + y = }")
    # print(x + 10) # TypeError


def recipe2():
    ax = np.array([1, 2, 3, 4])
    ay = np.array([5, 6, 7, 8])
    print(f"{ax * 2 = }")
    print(f"{ax + 10 = }")
    print(f"{ax + ay = }")
    print(f"{ax * ay = }")
    print(f"{np.sqrt(ax) = }")
    print(f"{np.cos(ax) = }")
    print(f"{f(ax) = }")


def recipe3():
    """ 一个10,000*10,000的浮点数二维网格 """
    start_time = time.time()

    grid = np.zeros(shape=(10000, 100000), dtype=float)
    # print(grid)
    grid += 10
    np.sin(grid)

    end_time = time.time()
    print(f"{'time cost: {:.2f} seconds'.format(end_time - start_time) = }")


def recipe4():
    """扩展Python列表的索引功能 - 特别是对于多维数组"""
    a = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
    print(f"{a = }")
    print(f"{a[1] = }")
    print(f"{a[:,1] = }")
    print(f"{a[1:3, 1:3] = }")

    a[1:3, 1:3] += 10
    print(f"{a = }")

    print(f"{a + [100, 101, 102, 103] = }")
    print(f"{a = }")

    print(f"{np.where(a < 10, a, 10) = }")


def f(x):
    """计算多项式的值"""
    return 3*x**2 - 2*x + 7


def main():
    print('recipe1'.center(20, '*'))
    recipe1()
    print('recipe2'.center(20, '*'))
    recipe2()
    print('recipe3'.center(20, '*'))
    recipe3()
    print('recipe4'.center(20, '*'))
    recipe4()


if __name__ == '__main__':
    main()
